<template>
  <st-form-panel title="新增商机" v-loading="loading">
    <div slot="btm">
      <el-button type="primary" @click="save">保存</el-button>
      <el-button type="primary" @click="$emit('list')">取消</el-button>
    </div>
    <div slot="content">
      <div class="content-top">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="商机名称：" prop="businessName">
                <el-input v-model="form.businessName" placeholder="请输入商机名称" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="商机阶段：" prop="statusId">
                <el-select
                  v-model="form.statusId"
                  placeholder="请输入商机阶段"
                  clearable
                >
                  <el-option
                    v-for="dict in dict.type.business_status_id"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>

              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="下次联系时间：" prop="nextTime">
                <el-date-picker
                  v-model="form.nextTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="请输入下次联系时间">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="预计成交日期：" prop="dealDate">
                <el-date-picker
                  v-model="form.dealDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请输入预计成交日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="商机来源：" prop="source">
                <el-select
                  v-model="form.source"
                  placeholder="请输入商机来源"
                  clearable
                >
                  <el-option
                    v-for="dict in dict.type.bussiness_source"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16">
              <el-form-item label="备注：" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="content-bottom">
        <el-row>
          <el-col :span="9">
            <el-button type="primary" @click="selectProduct">选择商品</el-button>
          </el-col >
          <el-col :span="15" style="font-size: 14px;
            text-align: right;">
           已添加产品: {{formData.dataList.length}}
            合计（元）：{{priceSum}}
            总折扣：<el-input style="width: 15%;" v-model="form.discountRate"></el-input>
            最终价格：<el-input style="width: 15%;" v-model="form.totalPrice"></el-input>
          </el-col>
        </el-row>

        <x-form ref="xForm" v-model="formData" :config="formConfig">
          <template #discount="scope">
               {{ (scope.row.salesPrice / scope.row.price).toFixed(2)}}
          </template>
          <template #subtotal="scope">
            {{scope.row.salesPrice * scope.row.productNum}}
          </template>
        </x-form>
      </div>
      <product-select ref="proSelect" @selected="productSelected"></product-select>
    </div>

  </st-form-panel>
</template>
<script >
import productSelect from '@/views/crm/components/productSelect.vue'
import { addBusiness,getBusiness,updateBusiness } from '@/api/crm/business'
export default {
  components:{
    productSelect
  },
  dicts:[
    'business_status_id',
    'bussiness_source'
  ],
  data(){
    return {
      loading:0,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      formData: {
        dataList: []
      },
      priceSum: 0,
      discountSum: 1,
      lastPrice:0,
      operateType:'add'
    }
  },
  watch:{
    'formData.dataList':{
      handler(newVal,oldVal){
        let salesPriceSum=0;
        let priceSum=1;
        this.formData.dataList.forEach((item)=>{
          salesPriceSum += item.salesPrice * item.productNum;
          priceSum=item.price * item.productNum;
        });
        console.log(salesPriceSum,priceSum);
        this.$set(this.form, 'discountRate',(salesPriceSum/priceSum).toFixed(2));
        this.$set(this.form, 'totalPrice',salesPriceSum);
        this.$set(this.form,'money',priceSum);
        this.priceSum=salesPriceSum;
      },
      deep: true,
     },
  },
  computed: {
    formConfig() {
      const _this = this
      return {
        inline: false,
        item: [
          {
            xType: 'table',
            table:{
              label: '商机关联产品列表',
              name: 'dataList',
              height: 'calc(100vh - 525px)',
              size: 'mini',
              operate: {
                show: true,
                label: '操作',
                width: '80px',
                headerAlign: 'center',
                align: 'center',
                btn: [
                  {
                    type: 'text',
                    text:'删除',
                    icon: 'el-icon-delete',
                    size: 'mini',
                    circle: true,
                    style: '',
                    className: '',
                    click:(arr, index) => {
                      _this._handleItem(arr, index)
                    }
                  }
                ]
              },
              column: [
                {
                  label: '产品名称',
                  name: 'productName',
                  width: '150'
                },
                {
                  label: '单位',
                  name: 'unit',
                  width: '230'
                },
                {
                  label: '产品价格',
                  name: 'price'
                },
                {
                  label: '售价',
                  name: 'salesPrice',
                  xType: 'input',
                  rules: [{ required: true, message: '请输入售价', trigger: ['blur', 'change'] }]
                },
                {
                  label: '数量',
                  name: 'productNum',
                  xType:'inputNumber',
                  rules: [{ required: true, message: '请输入数量', trigger: ['blur', 'change'] }]
                },
                {
                  label: '折扣',
                  name: 'discount',
                  slot:true,
                  },
                {
                  label: '合计',
                  name: 'subtotal',
                  xType: 'input',
                  slot:true
                }
              ]
            }
          }
        ]
      }
    }
  },
  methods:{
    show(data){
        this.formData.dataList.splice(0,this.formData.dataList.length);
        if(typeof data != "undefined"){
          this.reset();
          this.operateType='modify';
          this.loading++;
          getBusiness(data.businessId).then((res)=>{
              this.form=res.data;
              res.data.productList.forEach((item)=>{
                this.formData.dataList.push(item);
              })
              this.loading--;
          });
        }else{
          this.reset();
          this.operateType='add';
        }
    },

    selectProduct(){
      this.$refs.proSelect.show();
    },
    reset() {
      this.form = {
        businessId: null,
        businessName: null,
        money: null,
        statusId: null,
        nextTime: null,
        customerId: null,
        dealDate: null,
        discountRate: null,
        totalPrice: null,
        source: null,
        remark: null,
        roUserId: null,
        rwUserId: null,
        isEnd: null,
        createdBy: null,
        ownerUserId: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null
      };
      this.resetForm("form");
    },
    save() {
      this.loading++;
      this.$refs['xForm'].validate().then(() => {
        this.$set(this.form, 'productList', this.formData.dataList);
        if(this.operateType=='add'){
          addBusiness(this.form).then((res)=>{
            this.$emit("list")
          })
        }else{
          updateBusiness(this.form).then((res)=>{
            this.$emit("list");
          })
        }

        console.log(this.formData)
      }).catch(e => console.error(e)).finally(() => this.loading--)
    },
    productSelected(items){
      for (let i = 0; i < items.length; i++) {
        this.$set(items[i],'salesPrice',items[i].price);
        this.$set(items[i],'productNum', 1);
        this.formData.dataList.push(items[i]);
      }
      console.log(this.formData.dataList);
    },
    getTableHeight() {
      let tableHeight
      const allPanel = document.querySelectorAll('.form-panel-container')
      allPanel.forEach(item => {
        let titleHeight=item.querySelectorAll('.form-title')
        const height = item.clientHeight
          -titleHeight[0].clientHeight
        if (height > 0) {
          tableHeight = height
        }
      })
      console.log(tableHeight)
      return tableHeight
    },


  }

}
</script>
<style scoped lang="scss">
.el-form{
  padding: 10px 0 0 0;
}
.el-date-editor{
  width:100%;
}
.el-select{
  width: 100%;
}
</style>
